package com.lfy.fyadmin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lfy.fyadmin.common.R;
import com.lfy.fyadmin.entity.GroupPermission;
import com.lfy.fyadmin.service.GroupPermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/group-permission")
@Tag(name = "用户组权限关联管理", description = "用户组与权限关联关系接口")
public class GroupPermissionController {

    private final GroupPermissionService groupPermissionService;

    public GroupPermissionController(GroupPermissionService groupPermissionService) {
        this.groupPermissionService = groupPermissionService;
    }

    @PostMapping
    @Operation(summary = "新增用户组权限关联")
    public R<Boolean> save(@RequestBody GroupPermission groupPermission) {
        boolean result = groupPermissionService.save(groupPermission);
        return result ? R.ok(true) : R.fail("新增失败");
    }

    @PostMapping("/batch")
    @Operation(summary = "新增用户组权限关联")
    public R<Boolean> savebatch(@RequestBody List<GroupPermission> groupPermission) {
        boolean result = groupPermissionService.saveBatch(groupPermission);
        return result ? R.ok(true) : R.fail("新增失败");
    }

    @PutMapping
    @Operation(summary = "修改用户组权限关联")
    public R<Boolean> update(@RequestBody GroupPermission groupPermission) {
        boolean result = groupPermissionService.updateSelective(groupPermission);
        return result ? R.ok(true) : R.fail("修改失败");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户组权限关联")
    public R<Boolean> delete(@PathVariable Integer id) {
        boolean result = groupPermissionService.removeById(id);
        return result ? R.ok(true) : R.fail("删除失败");
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询用户组权限关联")
    public R<GroupPermission> getById(@PathVariable Integer id) {
        GroupPermission groupPermission = groupPermissionService.getById(id);
        return groupPermission != null ? R.ok(groupPermission) : R.fail("未找到关联");
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询用户组权限关联")
    public R<IPage<GroupPermission>> findPage(@RequestParam Integer pageNum,
                                               @RequestParam Integer pageSize,
                                              @RequestParam(required = false) Long groupId) {
        Page<GroupPermission> page = new Page<>(pageNum, pageSize);

        Page<GroupPermission> permissionPage = groupPermissionService.lambdaQuery()
                .eq(groupId != null, GroupPermission::getGroupId, groupId)
                .page(page);
        return R.ok(permissionPage);
    }
}